package logic

import (
	"context"
	"strconv"

	"probe-users/internal/errorx"
	"probe-users/internal/svc"
	"probe-users/internal/utils"
	"probe-users/pb/users"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserLogic {
	return &GetUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetUserLogic) GetUser(in *users.GetUserRequest) (*users.GetUserResponse, error) {
	// 参数验证
	if in.Token == "" {
		return nil, errorx.ErrTokenNotEmpty
	}

	// 解析Token
	claims, err := utils.ParseToken(in.Token, l.svcCtx.Config.JWTAuth.AccessSecret)
	if err != nil {
		return nil, err
	}

	// 确定要查询的用户ID
	var targetUserId int64
	if in.UserId == 0 {
		// 如果没有指定用户ID，则查询当前用户
		targetUserId = claims.UserId
	} else {
		// 检查是否有权限查询其他用户
		hasPermission, err := l.svcCtx.Enforcer.Enforce(strconv.FormatInt(claims.RoleId, 10), "user", "read:other")
		if err != nil {
			return nil, errors.Wrapf(err, "检查权限失败")
		}
		if !hasPermission {
			return nil, errorx.ErrPermissionDenied
		}
		targetUserId = in.UserId
	}

	// 查询用户
	user, err := l.svcCtx.UserModel.FindOne(targetUserId)
	if err != nil {
		return nil, errors.Wrapf(err, "查询用户失败: %d", targetUserId)
	}

	// 获取角色名称
	role, err := l.svcCtx.RoleModel.FindOne(user.RoleID)
	if err != nil {
		return nil, errors.Wrapf(err, "查询角色失败: %d", user.RoleID)
	}

	return &users.GetUserResponse{
		User: &users.User{
			Id:        user.ID,
			Username:  user.Username,
			Email:     user.Email,
			Phone:     user.Phone,
			Nickname:  user.Nickname,
			RoleId:    user.RoleID,
			RoleName:  role.Name,
			CreatedAt: user.CreatedAt.Unix(),
			UpdatedAt: user.UpdatedAt.Unix(),
		},
	}, nil
}
